package com.devunion.salon.persistence.dao;

import com.devunion.salon.persistence.Day;
import org.hibernate.Hibernate;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;

import java.io.Serializable;
import java.sql.Date;
import java.sql.SQLException;
import java.util.List;

/**
 * @author Viktar Liaskovich
 */
public class DayDao extends BaseDaoObject<Day> {
    public Day getByKey(Serializable key) {
        return (Day) getHibernateTemplate().get(Day.class, key);
    }

    public Day getDay(final Date date, final String username) {
        return (Day) getHibernateTemplate().execute(new HibernateCallback() {
            public Object doInHibernate(Session session) throws HibernateException, SQLException {
                List<Day> result = session.createQuery("select day from Day day, Login login where " +
                        "login.login = :username and day.created = :date and day.location = login.location")
                        .setParameter("username", username, Hibernate.STRING)
                        .setParameter("date", date, Hibernate.DATE)
                        .list();

                if (result == null || result.isEmpty()) {
                    return null;
                }

                return result.get(0);
            }
        });
    }
}